﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using JIG_SoftTemplate.Common;
using JIG_SoftTemplate.Common.Services;
using JIG_SoftTemplate.Models;
using JIG_SoftTemplate.Resources.Language;
using Microsoft.Win32;
using Wpf.Ui;
using Wpf.Ui.Controls;
using Wpf.Ui.Extensions;

namespace JIG_SoftTemplate.ViewModels
{
    public partial class SettingPageViewModel : ViewModelBase
    {
        private readonly Common.Services.NavigationService navigationService;
        private readonly IContentDialogService contentDialogService;
        private readonly LoggerService loggerService;
        private readonly JsonConfigService jsonConfigService;
        private readonly LangSwitchService langSwitchService;


        private AppConfigModel appConfig;

        public SettingPageViewModel(Common.Services.NavigationService navigationService,
            IContentDialogService contentDialogService,
            LoggerService loggerService,
            JsonConfigService jsonConfigService,
            LangSwitchService langSwitchService)
        {
            this.navigationService = navigationService;
            this.contentDialogService = contentDialogService;
            this.loggerService = loggerService;
            this.jsonConfigService = jsonConfigService;
            this.langSwitchService = langSwitchService;

            //初始化appConfig
            appConfig = new AppConfigModel();
            appConfig.Common = new CommonConfig();
        }

        #region 非绑定变量

        /// <summary>
        /// 旧显示语言
        /// </summary>
        private string defaultLang;

        #endregion

        #region 绑定变量

        /// <summary>
        /// 数据保存路径
        /// </summary>
        [ObservableProperty]
        private string dataStoragePath;

        /// <summary>
        /// 本地化语言
        /// </summary>
        private string selectedLang;
        public string SelectedLang
        {
            get { return selectedLang; }
            set
            {
                selectedLang = value;
                OnPropertyChanged();
                langSwitchService.LangSwitch(SelectedLang);
            }
        }

        #endregion



        #region 私有方法

        private async Task LoadAppConfig()
        {
            try
            {
                //读取配置文件
                var loadedConfig = await jsonConfigService.LoadConfigAsync(new AppConfigModel());

                if (loadedConfig != null)
                {
                    if (loadedConfig?.Common != null)
                    {
                        //读取Json配置到appConfig
                        appConfig.Common.DataStoragePath = loadedConfig.Common.DataStoragePath;
                        appConfig.Common.SelectedLang = loadedConfig.Common.SelectedLang;

                        //保存原始语言
                        defaultLang = appConfig.Common.SelectedLang;

                        //更新到绑定属性
                        DataStoragePath = appConfig.Common.DataStoragePath;
                        SelectedLang = appConfig.Common.SelectedLang;

                    }
                    else
                    {
                        throw new Exception("Json文件Common类别读取失败");
                    }
                }



                loggerService.Info("SettingPage保存配置成功");
            }
            catch (Exception ex)
            {
                loggerService.Error("SettingPage保存配置出错", ex);
                return;
            }
        }

        private async Task SaveSpecAsync()
        {
            try
            {
                //更新界面上数据到配置appConfig中
                appConfig.Common.DataStoragePath = DataStoragePath;
                appConfig.Common.SelectedLang = SelectedLang;

                //保存配置
                await jsonConfigService.SaveConfigAsync(appConfig);
                loggerService.Info("SettingPage保存配置成功");
            }
            catch (Exception ex)
            {
                loggerService.Error("SettingPage保存配置出错", ex);
                return;
            }
        }

        #endregion


        #region 中继命令

        /// <summary>
        /// 载入命令
        /// </summary>
        [RelayCommand]
        public async Task Loaded()
        {
            //读取json文件中的信息
            await LoadAppConfig();
        }


        /// <summary>
        /// Home按钮
        /// </summary>
        [RelayCommand]
        private void BtnHome()
        {
            SelectedLang = defaultLang;
            WeakReferenceMessenger.Default.Send(new VMMessage { IsSpecChanged = new WeakReference(false) });
            navigationService.Navigate<HomePageViewModel>();
        }

        /// <summary>
        /// 保存规格按钮
        /// </summary>
        /// <returns></returns>
        [RelayCommand]
        private async Task BtnSaveSpecAsync()
        {
            await App.Current.Dispatcher.InvokeAsync(async () =>
            {
                var result = await contentDialogService.ShowSimpleDialogAsync(
                new SimpleContentDialogCreateOptions()
                {
                    Title = Lang.ContentDialog_SaveSpec_Title,
                    Content = Lang.ContentDialog_SaveSpec_Content,

                    PrimaryButtonText = Lang.ContentDialog_SaveSpec_Btn1Text,
                    SecondaryButtonText = Lang.ContentDialog_SaveSpec_Btn2Text,
                    CloseButtonText = Lang.ContentDialog_SaveSpec_Btn3Text
                });

                if (result == ContentDialogResult.Primary)
                {
                    //保存规格
                    await SaveSpecAsync();
                    WeakReferenceMessenger.Default.Send(new VMMessage { IsSpecChanged = new WeakReference(true) });
                    navigationService.Navigate<HomePageViewModel>();
                }
                else if (result == ContentDialogResult.Secondary)
                {
                    SelectedLang = defaultLang;
                    WeakReferenceMessenger.Default.Send(new VMMessage { IsSpecChanged = new WeakReference(false) });
                    navigationService.Navigate<HomePageViewModel>();
                }
            });

        }

        /// <summary>
        /// 保存Data到新路径按钮
        /// </summary>
        [RelayCommand]
        private void BtnSelectNewPath()
        {
            OpenFolderDialog openFolderDialog = new OpenFolderDialog()
            {
                Multiselect = false,
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            };
            if (openFolderDialog.ShowDialog() != true)
            {
                return;
            }

            if (openFolderDialog.FolderNames.Length == 0)
            {
                return;
            }

            DataStoragePath = string.Join("\n", openFolderDialog.FolderNames);
        }

        #endregion
    }
}
